/* eslint-disable jsdoc/ts-no-empty-object-type */
// @ts-check
import { rehype } from "rehype";

const rehypeParsed = rehype();
/**
 * @param {string} content
 * @param {import('webpack').LoaderContext<{}>} loaderContext
 * @returns {string}
 */
function doSetDataInspect(content, loaderContext) {
  /**
   * @type import('hast').Root
   */
  let result;
  /**
   * @param {import('hast').RootContent} res
   */
  function walkNode(res) {
    if (res.type === "element") {
      if (res.tagName === "head") return;
      for (const el of res.children) walkNode(el);
      if (
        ["script", "style", "link", "noscript", "html"].includes(res.tagName)
      ) {
        return;
      }
      res.properties = {
        ...res.properties,
        // fit code-inspector-plugin
        "data-insp-path": `${loaderContext.resourcePath.replaceAll("\\", "/")}:${res.position?.start?.line || 0}:${res.position?.start?.column || 0}:${res.tagName}`,
      };
    }
  }
  try {
    result = rehypeParsed.parse(content);
    for (const el of result.children) walkNode(el);
  } catch (error) {
    if (error instanceof Error) loaderContext.emitError(error);

    return content;
  }

  return rehypeParsed.stringify(result);
}

export { doSetDataInspect };
